import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter_wan_android/application.dart';
import 'package:flutter_wan_android/arch/net/http_manager.dart';
import 'package:flutter_wan_android/arch/net/result_data.dart';
import 'package:flutter_wan_android/arch/ui/toast.dart';
import 'package:flutter_wan_android/common/api.dart';
import 'package:flutter_wan_android/event/event.dart';
import 'package:flutter_wan_android/event/event_bus.dart';
import 'package:flutter_wan_android/model/article.dart';
import 'package:flutter_wan_android/model/banner.dart';
import 'package:flutter_wan_android/page/web_page.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/res/theme.dart';
import 'package:flutter_wan_android/routes/route_util.dart';
import 'package:flutter_wan_android/routes/routes.dart';
import 'package:flutter_wan_android/widget/article_item.dart';
import 'package:flutter_wan_android/widget/refresh.dart';
import 'package:flutter_wan_android/widget/wan_appbar.dart';

import 'package:fluttertoast/fluttertoast.dart';


class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<BannerBean> _banners = [];

  List<Article> _articles = [];

  EasyRefreshController _controller = EasyRefreshController();

  var _pageIndex = 0;

  @override
  void initState() {
    _getBanner();
    _getArticles();
    super.initState();

    EventBusUtil.getInstance().on<String>().listen((event) {
      if(event == WEvent.EVENT_LOGIN){
        _pageIndex = 0;
        _getArticles();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventBusUtil.getInstance().destroy();
  }


  /// 获取banner数据
  _getBanner() async {
    ResultData result = await HttpManager.instance().get(Api.BANNER);
    if (result.success) {
      setState(() {
        _banners = getBannerList(result.data);
      });
    } else {
      Fluttertoast.showToast(msg: result.msg);
    }
  }

  /// 获取文章列表
  _getArticles() async {
    ResultData result =
        await HttpManager.instance().get("article/list/$_pageIndex/json", withLoading: false);

    _controller.finishRefresh();
    bind(_controller, result);

    if (result.success) {
      setState(() {
        if (_pageIndex == 0) {
          _articles = getArticleList(result.data["datas"]);
        } else {
          _articles.addAll(getArticleList(result.data["datas"]));
        }
      });
      _pageIndex++;
    } else {
      Fluttertoast.showToast(msg: result.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WanAppbar(context, titleStr: "首页", actions: [
        IconButton(
          icon: Icon(Icons.search),
          onPressed: (){
            RouteUtil.push(context, Routes.search);
          },
        )
      ]),
      // body: SafeArea(
      body: Container(
        color: wTheme.background,
        child: EasyRefresh(
          controller: _controller,
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          header: refreshHeader,
          footer: refreshFooter,
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              if (index == 0) {
                return _createBanner();
              } else {
                return ArticleItem(_articles[index - 1], onRefresh: (){
                  setState(() {
                    List<Article> newList = [];
                    newList.addAll(_articles);
                    newList[index - 1].collect = !(newList[index - 1].collect ?? false);
                    _articles = newList;
                  });
                });
              }
            },
            itemCount: _articles.length + 1,
          ),
          onRefresh: () async {
            _pageIndex = 0;
            _getArticles();
          },
          onLoad: () async {
            _getArticles();
          },
        ),
      ),
      // ),
    );
  }

  /// 创建banner
  _createBanner() {
    if (_banners.length == 0) return Container();

    return Container(
      height: 200,
      child: Swiper(
        pagination: SwiperPagination(
            alignment: Alignment.bottomRight,
            builder: DotSwiperPaginationBuilder(size: 8, activeSize: 8)),
        autoplay: true,
        itemCount: _banners.length,
        itemBuilder: (BuildContext context, int index) {
          var banner = _banners[index];

          return GestureDetector(
            onTap: (){
              RouteUtil.push(
                context,
                Routes.web,
                params: {"url": banner.url, "title": banner.title},
              );
            },
            child: Stack(
              children: [
                Positioned(
                  child: CachedNetworkImage(
                    imageUrl: banner.imagePath,
                    fit: BoxFit.fill,
                  ),
                  left: 0,
                  right: 0,
                  top: 0,
                  bottom: 0,
                ),

                // Positioned(
                //   child: Container(
                //     color: Color(0x33555555),
                //   ),
                //   left: 0,
                //   right: 0,
                //   bottom: 0,
                //   height: 40,
                // ),
                // Positioned(
                //   child: Text(
                //     banner.title,
                //     style: TextStyle(
                //       color: WColor.white,
                //       fontSize: 14,
                //     ),
                //     maxLines: 1,
                //     overflow: TextOverflow.ellipsis,
                //   ),
                //   left: 8,
                //   right: 8,
                //   bottom: 8,
                // )

              ],
            ),
          );
        },
      ),
    );
  }
}
